package com.hkjtgc.pcr_app.view;

import android.content.Context;
import android.graphics.Paint.FontMetrics;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.MotionEvent;

import com.hkjtgc.pcr_app.R;


/**
 * 右边有清除按钮的文本框
 *
 * <ul>
 * <li>使用 {@link #setOnTextChangedListener(OnTextChangedListener)} 设置文字改变时触发的监听器</li>
 * <li>使用 {@link #setOnTextClearListener(OnTextClearListener)} 设置文字清空时触发的监听器</li>
 * </ul>
 * <p>在 xml 直接引用即可</p>
 */
public class ClearableEditText extends androidx.appcompat.widget.AppCompatEditText implements TextWatcher {
    private Drawable left, right;
    private boolean downInRight; // 是否在右边区域按下
    private OnTextClearListener onTextClearListener;
    private OnTextChangedListener onTextChangedListener;

    public static interface OnTextClearListener {
        void onClear(ClearableEditText sender);
    }

    public static interface OnTextChangedListener {
        void onTextChanged(ClearableEditText sender, String text);
    }

    public ClearableEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public ClearableEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ClearableEditText(Context context) {
        super(context);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        Drawable right = getCompoundDrawables()[2];

        if (right != null) { // 有“X”按钮
            int right_pos = getWidth() - getPaddingRight() - right.getBounds().width();

            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                downInRight = event.getX() >= right_pos;

                if (downInRight) {
                    setDrawableRight(R.drawable.icon_delete_for_search_active);
                    return true;
                }
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                if (downInRight) {
                    setDrawableRight(R.drawable.icon_delete_for_search_default);

                    // 按下了右边的X，清除文本
                    Rect bounds = new Rect(0, 0, getWidth(), getHeight());
                    if (event.getX() >= right_pos && bounds.contains((int) event.getX(), (int) event.getY())) {
                        setText("");

                        if (onTextClearListener != null) {
                            onTextClearListener.onClear(this);
                        }
                        return true;
                    }
                }
            }
        }
        return super.onTouchEvent(event);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        addTextChangedListener(this);
    }

    /**
     * 设置文本框左边显示的图标
     *
     * @param resId
     *            图片资源ID
     */
    public void setDrawableLeft(int resId) {
        setDrawableLeft(getResources().getDrawable(resId));
    }

    /**
     * 设置文本框右边显示的图标
     *
     * @param resId
     *            图片资源ID
     */
    public void setDrawableRight(int resId) {
        setDrawableRight(getResources().getDrawable(resId));
    }

    /**
     * 设置文本框左边显示的图标
     *
     * @param drawable
     */
    public void setDrawableLeft(Drawable drawable) {
        left = drawable;
        if (drawable != null) {
            FontMetrics fm = this.getPaint().getFontMetrics();
            int height = (int) Math.ceil(fm.descent - fm.ascent);
            drawable.setBounds(0, 0, height, height);
        }
        setCompoundDrawables(left, null, right, null);
    }

    /**
     * 设置文本框右边显示的图标
     *
     * @param drawable
     */
    public void setDrawableRight(Drawable drawable) {
        right = drawable;
        if (drawable != null) {
            FontMetrics fm = this.getPaint().getFontMetrics();
            int height = (int) Math.ceil(fm.descent - fm.ascent);
            drawable.setBounds(0, 0, height, height);
        }
        setCompoundDrawables(left, null, right, null);
    }

    /**
     * 设置文字清空时触发的监听器
     *
     * @param onTextClearListener
     */
    public void setOnTextClearListener(OnTextClearListener onTextClearListener) {
        this.onTextClearListener = onTextClearListener;
    }

    /**
     * 设置文字改变时触发的监听器
     *
     * @param onTextChangedListener
     */
    public void setOnTextChangedListener(OnTextChangedListener onTextChangedListener) {
        this.onTextChangedListener = onTextChangedListener;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if (onTextChangedListener != null) {
            onTextChangedListener.onTextChanged(this, s.toString());
        }
        if (s.length() == 0) {
            setDrawableRight(null);
            // 文本清空时触发监听器
            if (onTextClearListener != null) {
                onTextClearListener.onClear(this);
            }
        } else {
            setDrawableRight(R.drawable.icon_delete_for_search_default);
        }
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

}
